﻿using ERPWinFormWork.Material.Material.Dtos;
using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Reflection;

namespace ERPWinFormWork.Material
{
    public partial class MaterialOutput : Form
    {
        public MaterialOutput()
        {
            InitializeComponent();
            // 绑定复选框的CheckedChanged事件
            cbonumber.CheckedChanged += Cbonumber_CheckedChanged;
        }

        // 存储选中的物料ID和单位ID，供后续使用
        private int _selectedMaterialId;
        private int _selectedUnitId;
        // 存储选中的领料人信息
        private string _selectedUser;
        // 存储选中的工单信息
        private string _selectedOrderId;
        private string _selectedOrderName;
        private string _selectedOrderNumber;
        // 存储选中的任务信息
        private string _selectedTaskNameId;
        private string _selectedTaskName;
        private string _selectedTaskNumber;
        private string _selectedRouting;
        private string _selectedProcessName;
        // 存储选中的仓库信息
        private string _selectedWarehouseName;
        private string _selectedWarehouseArea;
        private string _selectedStorageLocation;
        private string _selectedWarehouseAreaId;
        private string _selectedStorageLocationId;
        private string _selectedWarehouseNameId;

        /// <summary>
        /// 系统编号复选框状态改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Cbonumber_CheckedChanged(object sender, EventArgs e)
        {
            if (cbonumber.Checked)
            {
                // 勾选复选框时，自动生成领料单编号
                string autoNumber = GenerateMaterialOutputNumber();
                tbxoutputnumber.Text = autoNumber;
                tbxoutputnumber.ReadOnly = true; // 设置为只读，防止手动修改
            }
            else
            {
                // 取消勾选时，清空编号并允许手动输入
                tbxoutputnumber.Text = "请输入";
                tbxoutputnumber.ReadOnly = false;
            }
        }

        /// <summary>
        /// 生成领料单编号：LLDBH+年月日时分秒
        /// </summary>
        /// <returns>生成的编号</returns>
        private string GenerateMaterialOutputNumber()
        {
            DateTime now = DateTime.Now;
            string timeStamp = now.ToString("yyyyMMddHHmmss");
            return "LLDBH" + timeStamp;
        }
        /// <summary>
        /// 领料人
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnpeople_Click(object sender, EventArgs e)
        {
            People people = new People();
            if (people.ShowDialog() == DialogResult.OK)
            {
                // 获取选中的领料人信息并组合成完整信息填充到文本框中
                string teamName = people.SelectedPeopleName ?? "";
                string taskLeader = people.SelectedPeopleId ?? "";
                
                if (!string.IsNullOrEmpty(teamName) && !string.IsNullOrEmpty(taskLeader))
                {
                    // 组合班组名称和班组负责人，格式：班组名称+班组负责人
                    tbxpeople.Text = $"{teamName}{taskLeader}";
                    // 存储选中的领料人信息到MaterialOutputDtos的user字段
                    _selectedUser = $"{teamName}{taskLeader}";
                }
                else if (!string.IsNullOrEmpty(teamName))
                {
                    tbxpeople.Text = teamName;
                    _selectedUser = teamName;
                }
                else if (!string.IsNullOrEmpty(taskLeader))
                {
                    tbxpeople.Text = taskLeader;
                    _selectedUser = taskLeader;
                }
            }
        }
        /// <summary>
        /// 工单信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnordername_Click(object sender, EventArgs e)
        {
           Order order = new Order();
            if (order.ShowDialog() == DialogResult.OK)
            {
                // 获取选中的工单信息并填充到对应的文本框中
                if (!string.IsNullOrEmpty(order.SelectedWorkNumber))
                {
                    tbxorderid.Text = order.SelectedWorkNumber; // 工单编号填充到工艺编号文本框
                    _selectedOrderNumber = order.SelectedWorkNumber; // 存储工单编号
                }
                
                if (!string.IsNullOrEmpty(order.SelectedWorkName))
                {
                    tbxordernameoutput.Text = order.SelectedWorkName; // 工单名称填充到工单名称文本框
                    _selectedOrderName = order.SelectedWorkName; // 存储工单名称
                }
                
                // 存储工单ID（从工单编号中提取）
                if (!string.IsNullOrEmpty(order.SelectedWorkNumber))
                {
                    _selectedOrderId = GetIdFromText(order.SelectedWorkNumber).ToString();
                }
            }
        }
        /// <summary>
        /// 任务名称
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnrenwu_Click(object sender, EventArgs e)
        {
            TaskModel task = new TaskModel();
            if (task.ShowDialog() == DialogResult.OK)
            {
                // 获取选中的任务信息并填充到对应的文本框中
                if (!string.IsNullOrEmpty(task.SelectedTaskName))
                {
                    tbxordernameout.Text = task.SelectedTaskName; // 任务名称填充到任务名称文本框
                    _selectedTaskName = task.SelectedTaskName; // 存储任务名称
                }
                
                if (!string.IsNullOrEmpty(task.SelectedTaskNumber))
                {
                    tbxorderout.Text = task.SelectedTaskNumber; // 任务编号填充到任务编号文本框
                    _selectedTaskNumber = task.SelectedTaskNumber; // 存储任务编号
                }
                
                if (!string.IsNullOrEmpty(task.SelectedTechnologicalProcess))
                {
                    skinTextBox1.Text = task.SelectedTechnologicalProcess; // 工艺路线填充到工艺路线文本框
                    _selectedRouting = task.SelectedTechnologicalProcess; // 存储工艺路线
                }
                
                if (!string.IsNullOrEmpty(task.SelectedProcessName))
                {
                    tbxgongxu.Text = task.SelectedProcessName; // 工序名称填充到工序名称文本框
                    _selectedProcessName = task.SelectedProcessName; // 存储工序名称
                }
                
                // 存储任务ID（从任务编号中提取）
                if (!string.IsNullOrEmpty(task.SelectedTaskNumber))
                {
                    _selectedTaskNameId = GetIdFromText(task.SelectedTaskNumber).ToString();
                }
            }
        }
                /// <summary>
        /// 添加物料
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddMaterial_Click(object sender, EventArgs e)
        {
            AddMaterial material = new AddMaterial();
            if (material.ShowDialog() == DialogResult.OK)
            {
                // 获取选中的来料检验单数据
                var selectedItems = material.GetSelectedItems();
                if (selectedItems != null && selectedItems.Count > 0)
                {
                    // 获取第一个选中的项目
                    var firstItem = selectedItems.First();
                    
                    // 将检验单号填充到来料检验单号文本框中
                    tbxmaterialid1.Text = firstItem.MaterialNumber; // 物料编号
                    // 同时填充来料检验名称
                    tbxmaterialname1.Text = firstItem.MaterialName; // 物料名称
                    // 填充物料相关信息
                    tbxspecifications1.Text = firstItem.Specifications; // 规格型号
                    tbxunit1.Text = firstItem.Unit_Name; // 单位
                    
                    // 存储物料ID和单位ID到MaterialOutputDtos中
                    _selectedMaterialId = firstItem.Id; // 存储物料ID
                    if (firstItem.Unit_Id.HasValue)
                    {
                        // 这里可以将单位ID存储到类的字段中,供后续使用
                        _selectedUnitId = firstItem.Unit_Id.Value;
                    }
                    
                    // 显示选中的信息
                    MessageBox.Show($"已选择物料: {firstItem.MaterialName}\n物料编号: {firstItem.MaterialNumber}", 
                        "选择完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
        /// <summary>
        /// 仓库信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnwares1_Click(object sender, EventArgs e)
        {
            Warehouse warehouse = new Warehouse();
            if (warehouse.ShowDialog() == DialogResult.OK)
            {
                // 获取选中的仓库数据
                var selectedItems = warehouse.GetSelectedItems();
                if (selectedItems != null && selectedItems.Count > 0)
                {
                    // 获取第一个选中的项目
                    var firstItem = selectedItems.First();

                    // 将仓库名称填充到仓库名称文本框中
                    tbxwarehousename1.Text = firstItem.Warehouse_Name;
                    tbxarea1.Text = firstItem.Warehouse_Area;
                    tbxlocation1.Text = firstItem.Storage_location;

                    // 存储仓库信息
                    _selectedWarehouseName = firstItem.Warehouse_Name;
                    _selectedWarehouseArea = firstItem.Warehouse_Area;
                    _selectedStorageLocation = firstItem.Storage_location;

                    // 存储仓库ID信息（直接使用返回的ID，而不是从名称中提取）
                    _selectedWarehouseNameId = firstItem.WarehouseId.ToString();
                    _selectedWarehouseAreaId = firstItem.AreaId.ToString();
                    _selectedStorageLocationId = "1"; // 库位ID设为1，因为WarehouseOutput中没有库位ID字段

                    // 显示选中的信息
                    MessageBox.Show($"已选择仓库：{firstItem.Warehouse_Name}\n库位：{firstItem.Storage_location}\n库区：{firstItem.Warehouse_Area}",
                        "选择完成", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    // 如果选择了多个项目，可以在这里处理
                    if (selectedItems.Count > 1)
                    {
                        // 可以选择将多个仓库名称用逗号分隔显示，或者只显示第一个
                        // tbxwarehousename.Text = string.Join(", ", selectedItems.Select(x => x.Warehouse_Name));
                    }
                }
            }
        }
        
        /// <summary>
        /// 保存物料出库信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void skinButton2_Click(object sender, EventArgs e)
        {
            try
            {
                // 初始化物料出库对象
                AddMaterialOutputDtos materialOutput = new AddMaterialOutputDtos();

                // 基础校验
                if (string.IsNullOrWhiteSpace(tbxoutputnumber.Text) || tbxoutputnumber.Text == "请输入")
                {
                    MessageBox.Show("领料单编号不能为空!", "校验失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (string.IsNullOrWhiteSpace(tbxmaterialname1.Text))
                {
                    MessageBox.Show("物料名称不能为空!", "校验失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (string.IsNullOrWhiteSpace(tbxwarehousename1.Text))
                {
                    MessageBox.Show("仓库名称不能为空!", "校验失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (string.IsNullOrWhiteSpace(tbxCount.Text) || tbxCount.Text == "请输入")
                {
                    MessageBox.Show("出库数量不能为空!", "校验失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (string.IsNullOrWhiteSpace(tbxbatch1.Text) || tbxbatch1.Text == "请输入")
                {
                    MessageBox.Show("批次号不能为空!", "校验失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 赋值基础信息
                materialOutput.RequisitionNumber = tbxoutputnumber.Text.Trim();
                materialOutput.RequisitionName = tbxnameout.Text.Trim();
                materialOutput.RequisitionDate = DateTime.Now;

                // 设置领料人信息到 UserName（班组+负责人组合）
                materialOutput.UserName = string.IsNullOrWhiteSpace(tbxpeople.Text) ? "默认用户" : tbxpeople.Text.Trim();

                // 设置工单信息
                materialOutput.OrderId = !string.IsNullOrEmpty(_selectedOrderId) ? int.Parse(_selectedOrderId) : 1;
                materialOutput.OrderName = !string.IsNullOrWhiteSpace(_selectedOrderName)
                    ? _selectedOrderName
                    : (!string.IsNullOrWhiteSpace(tbxordernameoutput.Text) && tbxordernameoutput.Text != "请输入" ? tbxordernameoutput.Text.Trim() : "默认工单");
                materialOutput.OrderNumber = _selectedOrderNumber ?? "默认工单号";

                // 设置任务信息
                materialOutput.TaskNameId = !string.IsNullOrEmpty(_selectedTaskNameId) ? int.Parse(_selectedTaskNameId) : 1;
                materialOutput.TaskName = !string.IsNullOrWhiteSpace(_selectedTaskName)
                    ? _selectedTaskName
                    : (!string.IsNullOrWhiteSpace(tbxordernameout.Text) && tbxordernameout.Text != "请输入" ? tbxordernameout.Text.Trim() : "默认任务");
                materialOutput.TaskNumber = _selectedTaskNumber ?? "默认任务号";
                materialOutput.Routing = _selectedRouting ?? "默认工艺路线";
                materialOutput.ProcessName = _selectedProcessName ?? "默认工序";

                // 设置仓库信息
                materialOutput.Warehouse_Name = _selectedWarehouseName ?? "默认仓库";
                materialOutput.Warehouse_Area = _selectedWarehouseArea ?? "默认库区";
                materialOutput.Storage_location = _selectedStorageLocation ?? "默认库位";

                // 设置仓库ID信息
                //materialOutput.AreaId = !string.IsNullOrEmpty(_selectedWarehouseAreaId) ? int.Parse(_selectedWarehouseAreaId) : 1;
                //materialOutput.locationId = !string.IsNullOrEmpty(_selectedStorageLocationId) ? int.Parse(_selectedStorageLocationId) : 1;
                //materialOutput.Warehouse_Id = !string.IsNullOrEmpty(_selectedWarehouseNameId) ? int.Parse(_selectedWarehouseNameId) : 1;

                // 设置物料ID和物料详细信息
                materialOutput.Material_Id = _selectedMaterialId > 0 ? _selectedMaterialId : 1;
                materialOutput.MaterialNumber = !string.IsNullOrWhiteSpace(tbxmaterialid1.Text.Trim()) ? tbxmaterialid1.Text.Trim() : "1";
                materialOutput.MaterialName = !string.IsNullOrWhiteSpace(tbxmaterialname1.Text.Trim()) ? tbxmaterialname1.Text.Trim() : "默认物料";
                materialOutput.Specifications = !string.IsNullOrWhiteSpace(tbxspecifications1.Text.Trim()) ? tbxspecifications1.Text.Trim() : "默认规格";
                materialOutput.Unit_Name = !string.IsNullOrWhiteSpace(tbxunit1.Text.Trim()) ? tbxunit1.Text.Trim() : "个";

                // 解析批次号
                if (!string.IsNullOrWhiteSpace(tbxbatch1.Text) && tbxbatch1.Text != "请输入")
                {
                    if (int.TryParse(tbxbatch1.Text, out int batch))
                    {
                        materialOutput.Batch = batch;
                    }
                    else
                    {
                        materialOutput.Batch = 1; // 默认批次号
                    }
                }
                else
                {
                    materialOutput.Batch = 1; // 默认批次号
                }

                // 解析出库数量
                if (!int.TryParse(tbxCount.Text, out int quantity) || quantity <= 0)
                {
                    MessageBox.Show("出库数量必须是有效的正整数!", "校验失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                materialOutput.Quantity = quantity;



                // 设置其他必要字段
                materialOutput.Material_InOutType = 1; // 1表示出库
                materialOutput.Status = false; // 默认状态为禁用
                materialOutput.Note = ""; // 备注字段

                // 确保所有字符串字段不为null
                materialOutput.RequisitionName = !string.IsNullOrWhiteSpace(materialOutput.RequisitionName) ? materialOutput.RequisitionName : "默认领料单";
                materialOutput.RequisitionNumber = !string.IsNullOrWhiteSpace(materialOutput.RequisitionNumber) ? materialOutput.RequisitionNumber : "LLDBH000000000000";
                materialOutput.UserName = !string.IsNullOrWhiteSpace(materialOutput.UserName) ? materialOutput.UserName : "默认用户";
                materialOutput.OrderName = !string.IsNullOrWhiteSpace(materialOutput.OrderName) ? materialOutput.OrderName : "默认工单";
                materialOutput.OrderNumber = !string.IsNullOrWhiteSpace(materialOutput.OrderNumber) ? materialOutput.OrderNumber : "默认工单号";
                materialOutput.TaskName = !string.IsNullOrWhiteSpace(materialOutput.TaskName) ? materialOutput.TaskName : "默认任务";
                materialOutput.TaskNumber = materialOutput.TaskNumber ?? "默认任务号";
                materialOutput.Routing = materialOutput.Routing ?? "默认工艺路线";
                materialOutput.ProcessName = materialOutput.ProcessName ?? "默认工序";
                materialOutput.Warehouse_Name = materialOutput.Warehouse_Name ?? "默认仓库";
                materialOutput.Warehouse_Area = materialOutput.Warehouse_Area ?? "默认库区";
                materialOutput.Storage_location = materialOutput.Storage_location ?? "默认库位";

                // 调试信息：显示所有字段的赋值情况
                Console.WriteLine("=== 控件原始值 ===");
                Console.WriteLine($"tbxoutputnumber.Text: '{tbxoutputnumber.Text}'");
                Console.WriteLine($"tbxmaterialname1.Text: '{tbxmaterialname1.Text}'");
                Console.WriteLine($"tbxwarehousename1.Text: '{tbxwarehousename1.Text}'");
                Console.WriteLine($"tbxCount.Text: '{tbxCount.Text}'");
                Console.WriteLine($"tbxbatch1.Text: '{tbxbatch1.Text}'");
                Console.WriteLine($"tbxmaterialid1.Text: '{tbxmaterialid1.Text}'");
                Console.WriteLine($"tbxspecifications1.Text: '{tbxspecifications1.Text}'");
                Console.WriteLine($"tbxunit1.Text: '{tbxunit1.Text}'");
                Console.WriteLine($"tbxpeople.Text: '{tbxpeople.Text}'");
                Console.WriteLine("==================");

                // 调试信息：显示所有重要字段的赋值情况
                Console.WriteLine("=== 出库数据赋值结果 ===");
                Console.WriteLine($"RequisitionNumber: {materialOutput.RequisitionNumber}");
                Console.WriteLine($"RequisitionName: {materialOutput.RequisitionName}");
                Console.WriteLine($"RequisitionDate: {materialOutput.RequisitionDate}");
                //Console.WriteLine($"User: {materialOutput.User}");
                Console.WriteLine($"OrderId: {materialOutput.OrderId}");
                Console.WriteLine($"OrderName: {materialOutput.OrderName}");
                Console.WriteLine($"OrderNumber: {materialOutput.OrderNumber}");
                Console.WriteLine($"TaskNameId: {materialOutput.TaskNameId}");
                Console.WriteLine($"TaskName: {materialOutput.TaskName}");
                Console.WriteLine($"TaskNumber: {materialOutput.TaskNumber}");
                Console.WriteLine($"Routing: {materialOutput.Routing}");
                Console.WriteLine($"ProcessName: {materialOutput.ProcessName}");
                Console.WriteLine($"Warehouse_Name: {materialOutput.Warehouse_Name}");
                Console.WriteLine($"Warehouse_Area: {materialOutput.Warehouse_Area}");
                Console.WriteLine($"Storage_location: {materialOutput.Storage_location}");
                //Console.WriteLine($"AreaId: {materialOutput.AreaId}");
                //Console.WriteLine($"locationId: {materialOutput.locationId}");
                //Console.WriteLine($"Warehouse_Id: {materialOutput.Warehouse_Id}");
                Console.WriteLine($"Material_Id: {materialOutput.Material_Id}");
                Console.WriteLine($"MaterialNumber: {materialOutput.MaterialNumber}");
                Console.WriteLine($"MaterialName: {materialOutput.MaterialName}");
                Console.WriteLine($"Specifications: {materialOutput.Specifications}");
                Console.WriteLine($"Unit_Name: {materialOutput.Unit_Name}");
                Console.WriteLine($"Batch: {materialOutput.Batch}");
                Console.WriteLine($"Material_InOutType: {materialOutput.Material_InOutType}");
                Console.WriteLine($"Status: {materialOutput.Status}");
                Console.WriteLine($"Quantity: {materialOutput.Quantity}");
                Console.WriteLine($"Note: {materialOutput.Note}");
                Console.WriteLine("==================");

                // 提交请求
                await Add(materialOutput);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"构建出库数据时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine($"构建出库数据时发生异常：{ex}");
            }
        }

        /// <summary>
        /// 从文本中提取ID值
        /// </summary>
        /// <param name="text">包含ID的文本</param>
        /// <returns>提取的ID值，如果失败返回0</returns>
        private int GetIdFromText(string text)
        {
            try
            {
                // 如果文本本身就是数字，直接解析
                if (int.TryParse(text, out int id))
                    return id;
                
                // 如果文本包含数字，尝试提取
                var numbers = System.Text.RegularExpressions.Regex.Matches(text, @"\d+");
                if (numbers.Count > 0 && int.TryParse(numbers[0].Value, out int extractedId))
                    return extractedId;
                
                // 如果都失败了，返回0
                return 0;
            }
            catch
            {
                return 0;
            }
        }

       

        /// <summary>
        /// 发送POST请求
        /// </summary>
        private async Task Add(AddMaterialOutputDtos materialOutputData)
        {
            try
            {
                // 初始化API客户端
                var apiClient = new ApiClient(MaterialAppConfig.ApiBaseUrl);

                // 调试：先查询一下物料ID 6的入库数据，看看后端能查到什么
                Console.WriteLine("=== 调试：查询物料ID 6的入库数据 ===");
                try
                {
                    var debugParameters = new Dictionary<string, string>
                    {
                        ["PageIndex"] = "1",
                        ["PageSize"] = "1000",
                        ["Material_InOutType"] = "2" // 入库类型
                    };

                    var debugResponse = await apiClient.GetAsync<ApiResponse<List<AddMaterialOutputDtos>>>(
                        endpoint: "Material/GetMaterial_InOutboundShow",
                        parameters: debugParameters
                    );

                    if (debugResponse != null && debugResponse.code == 200 && debugResponse.pageData != null)
                    {
                        var material6Data = debugResponse.pageData.Where(x => x.Material_Id == 6).ToList();
                        Console.WriteLine($"找到物料ID 6的入库记录数量: {material6Data.Count}");
                        
                        foreach (var item in material6Data)
                        {
                            Console.WriteLine($"入库记录: ID={item.Id}, 数量={item.Quantity}, 状态={item.Status}, 批次={item.Batch}, 仓库={item.Warehouse_Name}");
                        }
                    }
                    else
                    {
                        Console.WriteLine($"查询入库数据失败: {debugResponse?.code} - {debugResponse?.message}");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"调试查询异常: {ex.Message}");
                }
                Console.WriteLine("=== 调试结束 ===");

                var response = await apiClient.PostAsync<AddMaterialOutputDtos, ApiResponse<string>>(
                    endpoint: "Material/AddMaterial_InOut",
                    data: materialOutputData
                );

                if (response != null && response.code == 200)
                {
                    MessageBox.Show("物料出库添加成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    // 刷新父列表并关闭当前窗体
                    try
                    {
                        var parent = Application.OpenForms.OfType<GetMaterial>().FirstOrDefault();
                        if (parent != null)
                        {
                            var method = typeof(GetMaterial).GetMethod("GetMaterialOutData", BindingFlags.Instance | BindingFlags.NonPublic);
                            method?.Invoke(parent, new object[] { null });
                        }
                    }
                    catch { }

                    this.Close();
                }
                else
                {
                    string errorMessage = response?.message ?? "未知错误";
                    MessageBox.Show($"提交失败: {errorMessage}\n错误代码: {response?.code}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Console.WriteLine($"API返回错误: {errorMessage}, 代码: {response?.code}");
                }
            }
            catch (System.Net.WebException webEx)
            {
                MessageBox.Show($"网络连接失败: {webEx.Message}\n请检查网络连接和服务器状态", "网络错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine($"网络异常: {webEx}");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"提交失败: {ex.Message}\n请检查数据格式是否正确", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine($"提交异常: {ex}");
            }
        }





        /// <summary>
        /// 清空表单
        /// </summary>
        private void ClearForm()
        {
            tbxoutputnumber.Text = "";
            tbxmaterialid1.Text = "";
            tbxmaterialname1.Text = "";
            tbxspecifications1.Text = "";
            tbxunit1.Text = "";
            tbxpeople.Text = "";
            tbxorderid.Text = "";
            tbxordernameout.Text = "";
            tbxorderout.Text = "";
            skinTextBox1.Text = "";
            tbxgongxu.Text = "";
            tbxwarehousename1.Text = "";
            tbxarea1.Text = "";
            tbxlocation1.Text = "";
            tbxCount.Text = "请输入";
            tbxbatch1.Text = "请输入";
            
            // 重置选中的ID
            _selectedMaterialId = 0;
            _selectedUnitId = 0;
            tbxmaterialid1.Text = "";
            // 重置选中的领料人信息
            _selectedUser = null;
            // 重置选中的工单信息
            _selectedOrderId = null;
            _selectedOrderName = null;
            _selectedOrderNumber = null;
            // 重置选中的任务信息
            _selectedTaskNameId = null;
            _selectedTaskName = null;
            _selectedTaskNumber = null;
            _selectedRouting = null;
            _selectedProcessName = null;
            // 重置选中的仓库信息
            _selectedWarehouseName = null;
            _selectedWarehouseArea = null;
            _selectedStorageLocation = null;
            _selectedWarehouseAreaId = null;
            _selectedStorageLocationId = null;
            _selectedWarehouseNameId = null;
            
            // 取消复选框选中状态
            cbonumber.Checked = false;
        }

       
        public class ApiResponse<T>
        {
            public int code { get; set; }
            public string message { get; set; }
            public string jwt { get; set; }
            public T pageData { get; set; }
            public T data { get; set; }
            public int totalCount { get; set; }
            public int totalPages { get; set; }
        }
    }
}
